package com.tudulist.web.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.http.handler.RedirectRequestHandler;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.security.web.savedrequest.SavedRequest;

/**
 * Utilities class
 * 
 * @author seif
 * 
 */
public final class TudulistUtil {

	public static final String TODOLISTID = "todolistid";

	/**
	 * formatting date time using pattern 
	 * @param date
	 * @return
	 */
	public static String doFormat(DateTime date) {
		DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
		return formatter.print(date);
	}

	/**
	 * Returns the URL the user accessed before he was redirected to the login
	 * page. This URL has been stored in the session by spring security.
	 * 
	 * @return the original URL the user accessed or null if no URL has been
	 *         stored in the session.
	 */
	public static String getOriginalUrl(HttpSession session) {
		SavedRequest savedRequest = (SavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
		if (savedRequest != null) {
			return savedRequest.getRedirectUrl();
		} else {
			return null;
		}
	}

	/**
	 * redirect to a url
	 * 
	 * @param url
	 */
	public static void redirectToUrl(String url) {
		RequestCycle.get().replaceAllRequestHandlers(new RedirectRequestHandler(url));
	}

	/**
	 * this method use the spring security's feature to logout a user
	 */
	public static void logout() {
		HttpServletRequest servletRequest = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
		redirectToUrl(servletRequest.getContextPath() + "/logout");
	}

}
